package cn.hacynn.nd.config;

import cn.hacynn.nd.common.properties.MailProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

@Configuration
public class JavaMailConfiguration {

    @Autowired
    private MailProperties mailProperties;

    @Bean
    JavaMailSenderImpl mailSender() {
        JavaMailSenderImpl sender = new JavaMailSenderImpl();
        this.applyProperties(mailProperties, sender);
        return sender;
    }

    private void applyProperties(MailProperties mailProperties, JavaMailSenderImpl sender) {
        sender.setHost(mailProperties.getHost());
        if (mailProperties.getPort() != null) {
            sender.setPort(mailProperties.getPort());
        }
        sender.setUsername(mailProperties.getUsername());
        sender.setPassword(mailProperties.getPassword());
        sender.setProtocol(mailProperties.getProtocol());
        if (mailProperties.getDefaultEncoding() != null) {
            sender.setDefaultEncoding(mailProperties.getDefaultEncoding().name());
        }

        sender.setJavaMailProperties(this.asProperties());
    }

    private Properties asProperties() {
        Properties properties = new Properties();
        Map<String, String> source = new HashMap<>();
        source.put("mail.smtp.auth", mailProperties.getSmtpAuth());
        source.put("mail.smtp.socketFactory.port", mailProperties.getSocketFactoryPort());
        source.put("mail.smtp.socketFactory.class", mailProperties.getSocketFactoryClass());
        source.put("mail.smtp.socketFactory.fallback", mailProperties.getSocketFactoryFallback());
        source.put("mail.smtp.starttls.enable", mailProperties.getStarttlsEnable());
        source.put("mail.smtp.starttls.required", mailProperties.getStarttlsRequired());
        properties.putAll(source);
        return properties;
    }

}
